package com.yiwyn.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author Yiwyn
 * @create 2023/1/30 23:09
 */
@RestController
public class DemoController {

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/test")
    public String test() {

        String key = "key";

        //尝试获取设置锁，并添加过期时间5分钟
        Boolean lock;
        try {
            lock = redisTemplate.opsForValue().setIfAbsent(key, "1", 5, TimeUnit.MINUTES);

            if (Boolean.TRUE.equals(lock)) {
                return "操作成功";
            }
            return "系统繁忙，请稍后重试";

        } finally {
            redisTemplate.delete(key);
        }
    }


    @GetMapping("/fre")
    public String fre(String userId) {

        Object o = redisTemplate.opsForValue().get(userId);
        if (o != null) {
            return "访问频率过高";
        } else {
            redisTemplate.opsForValue().set(userId, String.valueOf(System.currentTimeMillis()), 10, TimeUnit.SECONDS);
        }
        return "正常访问";
    }


    @GetMapping("/up")
    public String up(String username) {
        redisTemplate.boundHashOps("users").put(username, System.currentTimeMillis());
        return "up";
    }

    @GetMapping("/getcount")
    public String count() {
        Long users = redisTemplate.opsForHash().size("users");
        return String.valueOf(users);
    }

}
